package com.lecture.junit.tdd.example;

import exception.AccountAlreadyRevokedException;
import exception.AccountNotFoundException;
import exception.PasswordExpiredException;

/**
 * User: Yury
 */
public abstract class LoginServiceState {
	public final static int PASSWORD_EXPIRATION_AGE = 30;

	public void login(IAccount account, String password, LoginService context)
			throws AccountNotFoundException, AccountAlreadyRevokedException,
			PasswordExpiredException {

		if (account.passwordMatches(password)) {
			if (account.isRevoked()) {
				throw new AccountAlreadyRevokedException(
						"Account is already revoked");
			}

			int passwordAge = account.getPasswordAge(password);
			if (account.getPasswordAge(password) >= PASSWORD_EXPIRATION_AGE) {
				throw new PasswordExpiredException("Password age = "
						+ passwordAge + ". Must be less than "
						+ PASSWORD_EXPIRATION_AGE + ".");
			}

			account.setLoggedIn(true);
			context.setState(account.getUserName(), new FirstFailedAttempt());
		} else {
			dealWithFailedAttempt(account, context);
		}
	}

	protected abstract void dealWithFailedAttempt(IAccount acc,
			LoginService context);
}
